const { finduser, createuser } = require('../../service/shopper/login')
const axios = require('axios')
const jwt = require('jsonwebtoken')
module.exports = {
    async wxLogin(ctx, next) {
        const { code, nickName, gender, avatarUrl } = ctx.request.body
        const rudata = await axios.get("https://api.weixin.qq.com/sns/jscode2session", { params: { appid: "wxff89805ea4c21f37", secret: "d516a62ab120c9c0cc9d50d275c6b3d2", js_code: code, grant_type: "authorization_code" } })
        const hasuser = await finduser({ openid: rudata.data.openid })
        if (!hasuser) {
            await createuser({ openid: rudata.data.openid, name: nickName, xb: gender, img: avatarUrl })
            const finddata = await finduser({ openid: rudata.data.openid })
            return ctx.body = {
                code: 200,
                msg: "登录成功",
                data: finddata.dataValues,
                token: jwt.sign(finddata.dataValues, "ximo", { expiresIn: '1d' })
            }
        }
        return ctx.body = {
            code: 200,
            msg: "登录成功",
            data: hasuser.dataValues,
            token: jwt.sign(hasuser.dataValues, "ximo", { expiresIn: '1d' })
        }
    }
}